package cn.net.ecode.elec.api.web;

import cn.net.ecode.annotation.Login;
import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.utils.JedisUtils;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.constant.SendSmsTypeEnum;
import cn.net.ecode.util.R;
import cn.net.ecode.util.SendSmsUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @ClassName AppSmsController
 * @Description 短信验证码接口
 * @Author AlanShelby
 * @Date 2019-08-26 15:28:52 15:28
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/sms")
public class AppSmsController {

    /**
     * @Method getValidateCode
     * @Description 用户注册短信验证码
     * @Author AlanShelby
     * @Date 15:45 2019/8/26 0026
     * @Return cn.net.ecode.util.R
     */
    @RequestMapping(value = "/getValidateCode/{phoneNumber}", method = RequestMethod.GET)
    public R getValidateCode(@PathVariable String phoneNumber, @RequestParam String type) {
        String validateCode = SendSmsUtils.generateValidationCode();
        HashMap<String, String> params = new HashMap<>();
        params.put("code", validateCode);
        String validateCodeJson = JSON.toJSONString(params);

        // 发送短信
        String result = SendSmsUtils.sendSms(phoneNumber, validateCodeJson);

        // 校验是否发送成功
        JSONObject jsonObject = JSON.parseObject(result);
        String code = (String) jsonObject.get("Code");

        if (StringUtils.equals("OK", code)) {
            // 将验证码存入缓存，有效时间为5分钟
            String generateKey = null;
            if (StringUtils.equals(type, String.valueOf(SendSmsTypeEnum.REGISTER.getCode()))) {
                generateKey = JedisUtils.KEY_PREFIX + ":" + SendSmsTypeEnum.REGISTER.getCode() + ":" + phoneNumber;
            } else {
                generateKey = JedisUtils.KEY_PREFIX + ":" + SendSmsTypeEnum.LOGIN.getCode() + ":" + phoneNumber;
            }
            JedisUtils.set(generateKey, validateCode, Integer.parseInt(Global.getProperty("redis.expire")));
        } else {
            return R.error("发送短信失败");
        }

        return R.ok().put("validateCode", validateCode);
    }

    /**
     * @Method checkValidateCode
     * @Description 测试使用校验验证码是否过期
     * @Author AlanShelby
     * @Date 17:11 2019/8/26 0026
     * @Param [phoneNumber]
     * @Return cn.net.ecode.util.R
     */
    @Login
    @RequestMapping("/checkValidateCode/{phoneNumber}")
    public R checkValidateCode(@PathVariable String phoneNumber) {
        String generateKey = JedisUtils.KEY_PREFIX + ":" + SendSmsTypeEnum.REGISTER.getCode() + ":" + phoneNumber;

        String validateCode = JedisUtils.get(generateKey);
        if (validateCode == null) {
            return R.error("验证码已过期");
        }

        return R.ok();
    }
}
